<template>
  <div class="message-container">
    <div class="message-list">
      <div class="message-item" v-for="message in messages" :key="message.id" @click="goToMessageDetail(message.id)">
        <div class="message-content">
          <p :class="{ 'unread': !message.read }">{{ message.content }}</p>
          <span class="timestamp">{{ formatDate(message.timestamp) }}</span>
        </div>
        <button class="delete-btn" @click="deleteMessage(message.id)">删除</button>
      </div>
    </div>

    <div class="notice-box" v-if="messages.length === 0">
      <p>暂无消息通知。</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import axios from 'axios';
import { useUserStore } from '@/stores/userStore';
import { ElMessage } from 'element-plus';

const userStore = useUserStore();
const messages = ref([]);
const loading = ref(false);
const error = ref(null);
const currentUserId = ref('');
const isSeller = ref(false);

// 获取当前用户ID
const fetchCurrentUserId = () => {
  const user = userStore.user;
  if (user) {
    currentUserId.value = user.id;
    console.log('当前用户ID:', currentUserId.value);
  } else {
    currentUserId.value = '';
    console.log('用户未登录');
  }
};

// 格式化时间戳为可读日期
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 获取消息列表
const fetchMessages = async () => {
  loading.value = true;
  messages.value = [];
  
  try {
    if (!currentUserId.value) {
      ElMessage.warning('请先登录');
      return;
    }
    
    // 获取所有卖家消息
    const sellerMessagesResponse = await axios.get('http://localhost:3000/sellermessages');
    const allSellerMessages = sellerMessagesResponse.data || [];
    
    // 获取所有买家消息
    const buyerMessagesResponse = await axios.get('http://localhost:3000/buyermessages');
    const allBuyerMessages = buyerMessagesResponse.data || [];
    
    // 根据当前用户ID筛选消息
    let filteredMessages = [];
    
    // 检查当前用户ID是否与任何卖家消息中的sellerId匹配
    const sellerMessages = allSellerMessages.filter(msg => msg.sellerId === currentUserId.value);
    
    // 检查当前用户ID是否与任何买家消息中的userId匹配
    const buyerMessages = allBuyerMessages.filter(msg => msg.userId === currentUserId.value);
    
    // 合并筛选后的消息
    if (sellerMessages.length > 0) {
      isSeller.value = true;
      filteredMessages = sellerMessages;
      console.log('当前用户为卖家，获取卖家消息');
    } else if (buyerMessages.length > 0) {
      isSeller.value = false;
      filteredMessages = buyerMessages;
      console.log('当前用户为买家，获取买家消息');
    }
    
    // 按时间戳排序（最新的在前）
    filteredMessages.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
    
    messages.value = filteredMessages;
    console.log('获取消息成功:', messages.value);
  } catch (err) {
    error.value = err.message;
    ElMessage.error(`获取消息失败: ${err.message}`);
    console.error('消息获取错误:', err);
  } finally {
    loading.value = false;
  }
};

// 删除消息
const deleteMessage = async (id) => {
  try {
    // 确定消息类型
    const messageType = isSeller.value ? 'sellermessages' : 'buyermessages';
    
    await axios.delete(`http://localhost:3000/${messageType}/${id}`);
    messages.value = messages.value.filter(msg => msg.id !== id);
    ElMessage.success('消息已删除');
  } catch (err) {
    error.value = err.message;
    ElMessage.error('删除消息失败');
  }
};

// 查看消息详情并标记为已读
const goToMessageDetail = async (id) => {
  const messageToUpdate = messages.value.find(msg => msg.id === id);
  if (messageToUpdate && !messageToUpdate.read) {
    try {
      // 确定消息类型
      const messageType = isSeller.value ? 'sellermessages' : 'buyermessages';
      
      await axios.patch(`http://localhost:3000/${messageType}/${id}`, { read: true });
      messageToUpdate.read = true;
    } catch (err) {
      console.error('更新消息阅读状态失败', err);
    }
  }
  router.push({ path: `/main/profile/message-center/detail/${id}` });
};

// 监听用户ID变化，重新获取消息
watch(() => currentUserId.value, () => {
  if (currentUserId.value) {
    fetchMessages();
  }
});

onMounted(() => {
  fetchCurrentUserId();
});
</script>

<style scoped>
/* 样式保持不变 */
.message-container {
  padding: 20px;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message-item {
  background: #ffffff;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: transform 0.2s;
}

.message-item:hover {
  transform: translateY(-2px);
}

.unread {
  font-weight: bold;
}

.message-content p {
  margin: 0;
  margin-bottom: 5px;
}

.timestamp {
  color: #999;
  font-size: 12px;
}

.delete-btn {
  background: #e05649;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10px 20px;
  cursor: pointer;
  transition: background 0.3s;
}

.delete-btn:hover {
  background: #d04639;
}

.notice-box {
  margin-top: 20px;
  padding: 10px;
  background: #f8f8f8;
  border: 1px solid #eee;
  border-radius: 4px;
  color: #999;
  font-size: 14px;
  text-align: center;
}
</style>